<template>
  <div class="bookset-manager">
    <!-- 步骤导航 -->
    <div class="step-navigation">
      <div class="mode-indicator">
        <el-tag :type="isEditMode ? 'warning' : 'success'" size="large">
          {{ isEditMode ? '编辑模式' : '创建模式' }}
        </el-tag>
        <span class="mode-description">
          {{ isEditMode ? '正在编辑现有绘本集' : '正在创建新的绘本集' }}
        </span>
      </div>
      <el-steps :active="currentStep" align-center>
        <el-step title="基本信息" description="绘本集基础设置" />
        <el-step title="绘本管理" description="添加和管理绘本" />
        <el-step title="页面管理" description="编辑绘本页面" />
        <el-step title="预览提交" description="预览和保存" />
      </el-steps>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 左侧编辑区域 -->
        <el-col :span="16">
          <div class="edit-area">
            <!-- 步骤1：基本信息 -->
            <div v-show="currentStep === 0" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>📖 绘本集基本信息</span>
                  </div>
                </template>

                <el-form ref="basicFormRef" :model="bookSetData.basic" :rules="basicFormRules" label-width="120px">
                  <el-form-item label="绘本集标题" prop="title">
                    <el-input
                      v-model="bookSetData.basic.title"
                      placeholder="请输入绘本集标题"
                      maxlength="50"
                      show-word-limit
                    />
                  </el-form-item>

                  <el-form-item label="语言类型" prop="language">
                    <el-select v-model="bookSetData.basic.language" placeholder="请选择语言类型" style="width: 100%">
                      <el-option label="英文" value="en" />
                      <el-option label="中文" value="zh" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="分类" prop="categoryId">
                    <el-select v-model="bookSetData.basic.categoryId" placeholder="请选择分类" style="width: 100%">
                      <el-option
                        v-for="category in filteredCategories"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"
                      />
                    </el-select>
                    <div class="category-tips">
                      <el-text size="small" type="info">
                        💡 分类会根据选择的语言类型自动筛选
                      </el-text>
                    </div>
                  </el-form-item>

                  <el-form-item label="适龄范围" prop="ageRange">
                    <div class="age-range-container">
                      <el-select
                        v-model="bookSetData.basic.ageRange"
                        placeholder="请选择适龄范围"
                        style="width: 100%"
                        filterable
                        allow-create
                        @change="handleAgeRangeChange"
                        @blur="handleAgeRangeBlur"
                      >
                        <el-option label="0-2岁 (婴幼儿)" value="0-2岁" />
                        <el-option label="2-3岁 (学步期)" value="2-3岁" />
                        <el-option label="3-4岁 (幼儿园小班)" value="3-4岁" />
                        <el-option label="4-5岁 (幼儿园中班)" value="4-5岁" />
                        <el-option label="5-6岁 (幼儿园大班)" value="5-6岁" />
                        <el-option label="6-7岁 (学前班)" value="6-7岁" />
                        <el-option label="7-8岁 (小学一年级)" value="7-8岁" />
                        <el-option label="8-9岁 (小学二年级)" value="8-9岁" />
                        <el-option label="9-10岁 (小学三年级)" value="9-10岁" />
                        <el-option label="10-12岁 (小学高年级)" value="10-12岁" />
                        <el-option label="3-6岁 (学龄前)" value="3-6岁" />
                        <el-option label="6-12岁 (小学阶段)" value="6-12岁" />
                        <el-option label="0-12岁 (全年龄段)" value="0-12岁" />
                      </el-select>
                      <div class="age-range-tips">
                        <el-text size="small" type="info">
                          💡 可选择预设范围或输入自定义范围（如：4-7岁）
                        </el-text>
                      </div>
                    </div>
                  </el-form-item>

                  <el-form-item label="难度等级" prop="difficultyLevel">
                    <el-select v-model="bookSetData.basic.difficultyLevel" placeholder="请选择难度等级" style="width: 100%">
                      <el-option label="入门" value="beginner" />
                      <el-option label="中级" value="intermediate" />
                      <el-option label="高级" value="advanced" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="绘本集描述" prop="description">
                    <el-input
                      v-model="bookSetData.basic.description"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入绘本集描述"
                      maxlength="500"
                      show-word-limit
                    />
                  </el-form-item>

                  <el-form-item label="来源" prop="source">
                    <el-input
                      v-model="bookSetData.basic.source"
                      placeholder="请输入绘本集来源（如：牛津大学出版社）"
                      maxlength="100"
                      show-word-limit
                    />
                    <div class="source-tips">
                      <el-text size="small" type="info">
                        💡 标识绘本集的来源或出版社，便于分类管理
                      </el-text>
                    </div>
                  </el-form-item>

                  <el-form-item label="是否推荐" prop="isRecommended">
                    <el-switch
                      v-model="bookSetData.basic.isRecommended"
                      active-text="推荐"
                      inactive-text="不推荐"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                    />
                    <div class="recommend-tips">
                      <el-text size="small" type="info">
                        💡 推荐的绘本集将在首页和推荐列表中优先展示
                      </el-text>
                    </div>
                  </el-form-item>

                  <el-form-item label="绘本集封面" prop="coverUrl">
                    <div class="upload-section">
                      <el-upload
                        class="cover-uploader"
                        :action="getBusinessUploadUrl('bookset-cover', bookSetId || 0)"
                        :headers="getBusinessUploadHeaders()"
                        :show-file-list="false"
                        :on-success="handleCoverSuccess"
                        :before-upload="beforeCoverUpload"
                        accept="image/*"
                        name="cover"
                      >
                        <img v-if="bookSetData.basic.coverUrl" :src="bookSetData.basic.coverUrl" class="cover-image" />
                        <div v-else class="cover-placeholder">
                          <el-icon class="cover-icon"><Plus /></el-icon>
                          <div class="cover-text">点击上传绘本集封面</div>
                        </div>
                      </el-upload>
                      <div class="upload-tip">
                        <el-text type="info" size="small">
                          <el-icon><InfoFilled /></el-icon>
                          这是整个绘本集的封面图片，将显示在绘本集列表中
                        </el-text>
                      </div>
                    </div>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>

            <!-- 步骤2：绘本管理 -->
            <div v-show="currentStep === 1" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>📚 绘本管理</span>
                    <el-button type="primary" @click="addBook">添加绘本</el-button>
                  </div>
                </template>

                <div v-if="bookSetData.books.length === 0" class="empty-state">
                  <el-empty description="还没有添加绘本">
                    <el-button type="primary" @click="addBook">添加第一个绘本</el-button>
                  </el-empty>
                </div>

                <div v-else class="books-list">
                  <el-row :gutter="20">
                    <el-col
                      v-for="(book, index) in bookSetData.books"
                      :key="book.id || index"
                      :span="8"
                      style="margin-bottom: 20px;"
                    >
                      <el-card class="book-card">
                        <template #header>
                          <div class="book-header">
                            <span>绘本 {{ index + 1 }}</span>
                            <div class="book-actions">
                              <el-button size="small" type="primary" @click="editBook(index)">编辑</el-button>
                              <el-button size="small" type="danger" @click="removeBook(index)">删除</el-button>
                            </div>
                          </div>
                        </template>

                        <div class="book-display">
                          <div class="book-cover-container">
                            <img v-if="book.coverUrl" :src="book.coverUrl" class="book-cover" />
                            <div v-else class="cover-placeholder">
                              <el-icon><Picture /></el-icon>
                              <div>暂无封面</div>
                            </div>
                          </div>

                          <div class="book-info">
                            <h4>{{ book.title || '未命名绘本' }}</h4>
                            <p class="book-description">{{ book.description || '暂无描述' }}</p>
                            <div class="book-stats">
                              <el-tag size="small" type="info">{{ book.pages?.length || 0 }} 页</el-tag>
                              <el-tag size="small" type="success">排序: {{ book.sort || index + 1 }}</el-tag>
                            </div>
                          </div>
                        </div>
                      </el-card>
                    </el-col>
                  </el-row>
                </div>
              </el-card>
            </div>

            <!-- 步骤3：页面管理 -->
            <div v-show="currentStep === 2" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>📄 页面管理</span>
                    <div class="header-actions">
                      <el-select v-model="selectedBookIndex" placeholder="选择绘本" clearable style="width: 200px; margin-right: 10px;">
                        <el-option
                          v-for="(book, index) in bookSetData.books"
                          :key="index"
                          :label="`${book.title || '未命名绘本'} (${book.pages?.length || 0}页)`"
                          :value="index"
                        />
                      </el-select>
                      <el-button type="primary" @click="addPage" :disabled="selectedBookIndex === null">
                        添加页面
                      </el-button>
                      <el-button
                        type="success"
                        size="small"
                        :loading="batchTranslating"
                        :disabled="selectedBookIndex === null || !hasEnglishPagesWithoutTranslation"
                        @click="handleBatchTranslate"
                      >
                        <el-icon v-if="!batchTranslating"><MagicStick /></el-icon>
                        {{ batchTranslating ? '批量翻译中...' : '批量AI翻译' }}
                      </el-button>
                    </div>
                  </div>
                </template>

                <div v-if="selectedBookIndex === null" class="empty-state">
                  <el-empty description="请先选择一个绘本来管理页面" />
                </div>

                <div v-else-if="currentBook.pages.length === 0" class="empty-state">
                  <el-empty description="该绘本还没有页面">
                    <el-button type="primary" @click="addPage">添加第一页</el-button>
                  </el-empty>
                </div>

                <div v-else class="pages-container">
                  <div class="pages-grid">
                    <div
                      v-for="(page, pageIndex) in currentBook.pages"
                      :key="page.id || pageIndex"
                      class="page-item"
                    >
                      <el-card class="page-card">
                        <template #header>
                          <div class="page-header">
                            <span>第 {{ page.pageNumber || pageIndex + 1 }} 页</span>
                            <div class="page-actions">
                              <el-button size="small" type="primary" @click="editPage(pageIndex)">编辑</el-button>
                              <el-button size="small" type="danger" @click="removePage(pageIndex)">删除</el-button>
                            </div>
                          </div>
                        </template>

                        <div class="page-display">
                          <div class="page-image-container">
                            <img v-if="page.imageUrl" :src="page.imageUrl" class="page-image" />
                            <div v-else class="image-placeholder">
                              <el-icon><Picture /></el-icon>
                              <div>暂无图片</div>
                            </div>
                          </div>

                          <div class="page-content">
                            <div class="text-content">
                              <p>{{ page.textContent || '暂无文本内容' }}</p>
                            </div>

                            <div v-if="page.officialAudioUrl" class="audio-info">
                              <span class="label">音频：</span>
                              <el-tag type="success" size="small">已上传</el-tag>
                            </div>
                          </div>
                        </div>
                      </el-card>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>

            <!-- 步骤4：预览提交 -->
            <div v-show="currentStep === 3" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>🔍 最终预览</span>
                  </div>
                </template>

                <div class="final-preview">
                  <el-alert
                    :title="validationResult.title"
                    :type="validationResult.type"
                    :description="validationResult.description"
                    show-icon
                    :closable="false"
                    style="margin-bottom: 20px"
                  />

                  <div class="bookset-overview">
                    <h3>绘本集信息</h3>
                    <div class="info-grid">
                      <div class="info-item">
                        <span class="label">标题：</span>
                        <span>{{ bookSetData.basic.title || '未设置' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">语言：</span>
                        <span>{{ getLanguageText(bookSetData.basic.language) }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">来源：</span>
                        <span>{{ bookSetData.basic.source || '未设置' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">推荐状态：</span>
                        <el-tag :type="bookSetData.basic.isRecommended ? 'success' : 'info'" size="small">
                          {{ bookSetData.basic.isRecommended ? '推荐' : '普通' }}
                        </el-tag>
                      </div>
                      <div class="info-item">
                        <span class="label">绘本数量：</span>
                        <span>{{ bookSetData.books.length }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">总页数：</span>
                        <span>{{ totalPages }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-col>

        <!-- 右侧预览区域 -->
        <el-col :span="8">
          <div class="preview-area">
            <el-card class="preview-card">
              <template #header>
                <div class="preview-header">
                  <span>实时预览</span>
                  <el-tag :type="getValidationTagType()">{{ getValidationText() }}</el-tag>
                </div>
              </template>

              <div class="preview-content">
                <div v-if="currentStep === 0" class="step-preview">
                  <h4>绘本集基本信息</h4>
                  <div v-if="bookSetData.basic.coverUrl" class="cover-section">
                    <img :src="bookSetData.basic.coverUrl" class="preview-cover" />
                  </div>
                  <div class="info-section">
                    <div class="info-item">
                      <span class="label">标题：</span>
                      <span>{{ bookSetData.basic.title || '未设置' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">语言：</span>
                      <span>{{ getLanguageText(bookSetData.basic.language) }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">来源：</span>
                      <span>{{ bookSetData.basic.source || '未设置' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">推荐状态：</span>
                      <el-tag :type="bookSetData.basic.isRecommended ? 'success' : 'info'" size="small">
                        {{ bookSetData.basic.isRecommended ? '推荐' : '普通' }}
                      </el-tag>
                    </div>
                  </div>
                </div>

                <div v-else-if="currentStep === 1" class="step-preview">
                  <h4>绘本列表 ({{ bookSetData.books.length }}个)</h4>
                  <div v-if="bookSetData.books.length === 0" class="empty-preview">
                    <el-empty description="还没有添加绘本" :image-size="80" />
                  </div>
                  <div v-else class="books-preview">
                    <div
                      v-for="(book, index) in bookSetData.books"
                      :key="index"
                      class="book-preview-item"
                    >
                      <div class="book-cover">
                        <img v-if="book.coverUrl" :src="book.coverUrl" class="book-cover-img" />
                        <div v-else class="no-cover">无封面</div>
                      </div>
                      <div class="book-info">
                        <div class="book-title">{{ book.title || '未命名绘本' }}</div>
                        <div class="book-stats">
                          <el-tag size="small">{{ book.pages?.length || 0 }} 页</el-tag>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div v-else-if="currentStep === 2" class="step-preview">
                  <h4>页面总览</h4>
                  <div class="pages-stats">
                    <div class="stat-item">
                      <div class="stat-number">{{ totalPages }}</div>
                      <div class="stat-label">总页数</div>
                    </div>
                  </div>
                </div>

                <div v-else-if="currentStep === 3" class="step-preview">
                  <h4>完整预览</h4>
                  <div class="final-stats">
                    <div class="stats-grid">
                      <div class="stat-card">
                        <div class="stat-number">{{ bookSetData.books.length }}</div>
                        <div class="stat-label">绘本</div>
                      </div>
                      <div class="stat-card">
                        <div class="stat-number">{{ totalPages }}</div>
                        <div class="stat-label">页面</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 底部操作栏 -->
    <div class="footer-actions">
      <el-button @click="handleClose">取消</el-button>
      <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
      <el-button v-if="currentStep < 3" type="primary" @click="nextStep" :disabled="!canProceed">
        下一步
      </el-button>
      <el-button v-if="currentStep === 3" type="success" @click="handleSubmit" :loading="submitting">
        {{ isEditMode ? '更新绘本集' : '创建绘本集' }}
      </el-button>
    </div>

    <!-- 绘本编辑弹窗 -->
    <el-dialog
      v-model="bookEditVisible"
      title="编辑绘本"
      width="800px"
      :close-on-click-modal="false"
      class="book-edit-dialog"
      :z-index="3000"
      :modal="true"
      :append-to-body="true"
    >
      <el-form ref="bookFormRef" :model="editingBook" :rules="bookFormRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="绘本标题" prop="title">
              <el-input
                v-model="editingBook.title"
                placeholder="请输入绘本标题"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="editingBook.sort"
                :min="1"
                :max="100"
                placeholder="排序"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="绘本描述" prop="description">
          <el-input
            v-model="editingBook.description"
            type="textarea"
            :rows="3"
            placeholder="请输入绘本描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="绘本封面" prop="coverUrl">
          <div class="upload-section">
            <el-upload
              class="book-cover-uploader"
              :action="bookCoverUploadUrl"
              :headers="getBusinessUploadHeaders()"
              :show-file-list="false"
              :on-success="handleBookCoverSuccess"
              :before-upload="beforeBookCoverUpload"
              accept="image/*"
              name="cover"
            >
              <img v-if="editingBook.coverUrl" :src="editingBook.coverUrl" class="book-cover-image" />
              <div v-else class="book-cover-placeholder">
                <el-icon class="cover-icon"><Plus /></el-icon>
                <div class="cover-text">点击上传绘本封面</div>
              </div>
            </el-upload>
            <div class="upload-tip">
              <el-text type="warning" size="small">
                <el-icon><InfoFilled /></el-icon>
                这是单个绘本的封面，仅用于该绘本的显示
              </el-text>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelBookEdit">取消</el-button>
          <el-button type="primary" @click="saveBookEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 页面编辑弹窗 -->
    <el-dialog
      v-model="pageEditVisible"
      title="编辑页面"
      width="900px"
      :close-on-click-modal="false"
      class="page-edit-dialog"
    >
      <el-form ref="pageFormRef" :model="editingPage" :rules="pageFormRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="页面编号" prop="pageNumber">
              <el-input-number
                v-model="editingPage.pageNumber"
                :min="1"
                :max="100"
                placeholder="请输入页面编号"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="页面图片" prop="imageUrl">
              <div class="page-image-uploader">
                <el-upload
                  :action="pageImageUploadUrl"
                  :headers="{ Authorization: 'Bearer ' + getAccessToken() }"
                  :show-file-list="false"
                  :on-success="handlePageImageSuccess"
                  :before-upload="beforePageImageUpload"
                  accept="image/*"
                  name="page"
                >
                  <img v-if="editingPage.imageUrl" :src="editingPage.imageUrl" class="page-image-preview" />
                  <div v-else class="page-image-placeholder">
                    <el-icon><Plus /></el-icon>
                    <div>点击上传页面图片</div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="页面文本" prop="textContent">
              <el-input
                v-model="editingPage.textContent"
                type="textarea"
                :rows="4"
                placeholder="请输入页面文本内容"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="中文翻译" prop="chineseTranslation" v-if="editingPage.textLanguage === 'english'">
              <div class="translation-input-container">
                <el-input
                  v-model="editingPage.chineseTranslation"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入中文翻译内容（仅英文绘本需要）"
                  maxlength="2000"
                  show-word-limit
                  class="translation-textarea"
                />
                <el-button
                  type="primary"
                  size="small"
                  :loading="aiTranslating"
                  :disabled="!editingPage.textContent || !editingPage.textContent.trim()"
                  @click="handleAiTranslate"
                  class="ai-translate-btn"
                >
                  <el-icon v-if="!aiTranslating"><MagicStick /></el-icon>
                  {{ aiTranslating ? '翻译中...' : 'AI翻译' }}
                </el-button>
              </div>
              <div class="form-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>为英文绘本提供中文翻译，帮助用户理解内容。可使用AI翻译功能快速生成翻译</span>
              </div>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="文本语言" prop="textLanguage">
                  <el-select v-model="editingPage.textLanguage" placeholder="请选择文本语言" style="width: 100%">
                    <el-option label="英文" value="english" />
                    <el-option label="中文" value="chinese" />
                    <el-option label="双语" value="bilingual" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="阅读难度" prop="readingDifficulty">
                  <el-select v-model="editingPage.readingDifficulty" placeholder="请选择阅读难度" style="width: 100%">
                    <el-option label="简单" value="easy" />
                    <el-option label="中等" value="medium" />
                    <el-option label="困难" value="hard" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="官方音频" prop="officialAudioUrl">
              <div class="page-audio-uploader">
                <el-upload
                  :action="pageAudioUploadUrl"
                  :headers="{ Authorization: 'Bearer ' + getAccessToken() }"
                  :show-file-list="false"
                  :on-success="handleAudioSuccess"
                  :before-upload="beforeAudioUpload"
                  accept="audio/*"
                  name="audio"
                >
                  <el-button type="primary">
                    <el-icon><UploadFilled /></el-icon>
                    上传音频
                  </el-button>
                </el-upload>
                <div v-if="editingPage.officialAudioUrl" class="audio-preview">
                  <audio :src="editingPage.officialAudioUrl" controls style="width: 100%; margin-top: 10px;"></audio>
                  <el-button size="small" type="danger" @click="removeAudio" style="margin-top: 5px;">删除音频</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="关键词">
          <el-input
            v-model="keyWordsInput"
            placeholder="请输入关键词，用逗号分隔"
            @blur="updateKeyWords"
          />
          <div v-if="editingPage.keyWords.length > 0" class="keywords-display" style="margin-top: 10px;">
            <el-tag
              v-for="(keyword, index) in editingPage.keyWords"
              :key="index"
              closable
              @close="removeKeyword(index)"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ keyword }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPageEdit">取消</el-button>
          <el-button type="primary" @click="savePageEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, UploadFilled, InfoFilled, MagicStick } from '@element-plus/icons-vue'
import { getAccessToken } from '@/utils/auth'
import request from '@/config/axios'
import { createBookSet, updateBookSet, getBookSet, getNextBookSetId, updateBookSetBookCount, type BookSetCreateReqVO, type BookSetUpdateReqVO } from '@/api/reading/bookset'
import { createPictureBook, batchCreatePictureBooks, getPictureBooksByBookSetId, updatePictureBook, deletePictureBook, getNextPictureBookId, type PictureBookCreateReqVO, type PictureBookUpdateReqVO } from '@/api/reading/book'
import { createBookPage, batchCreateBookPages, getBookPagesByBookId, updateBookPage, deleteBookPage, getNextBookPageId, type BookPageCreateReqVO, type BookPageUpdateReqVO } from '@/api/reading/page'
import { translateText } from '@/api/reading/ai'

// 定义组件属性
interface Props {
  bookSetId?: number | null
  mode?: 'create' | 'edit'
}

const props = withDefaults(defineProps<Props>(), {
  bookSetId: null,
  mode: 'create'
})

// 定义组件事件
const emit = defineEmits(['close', 'success'])

// 当前步骤
const currentStep = ref(0)

// 提交状态
const submitting = ref(false)

// 编辑模式
const isEditMode = computed(() => props.mode === 'edit' && !!props.bookSetId)

// 绘本集ID（编辑模式使用真实ID，创建模式使用预分配ID）
const bookSetId = ref<number | null>(props.bookSetId)

// 定义类型接口
interface BookPage {
  id?: number
  pageNumber: number
  imageUrl: string
  imageWidth?: number
  imageHeight?: number
  textContent: string
  chineseTranslation?: string
  textLanguage?: string
  officialAudioUrl: string
  audioDuration?: number
  readingDifficulty?: string
  keyWords: string[]
  isNewPage?: boolean // 标记是否为新添加的页面
}

interface Book {
  id?: number
  title: string
  description: string
  coverUrl: string
  sort: number
  pages: BookPage[]
  isNewBook?: boolean // 标记是否为新添加的绘本
}

// 绘本集数据
const bookSetData = reactive({
  basic: {
    title: '',
    description: '',
    coverUrl: '',
    categoryId: null as number | null,
    language: 'en',
    difficultyLevel: '',
    ageRange: '',
    source: '',
    isRecommended: false,
    isActive: true
  },
  books: [] as Book[]
})

// 表单引用
const basicFormRef = ref()

// 选中的绘本索引
const selectedBookIndex = ref<number | null>(null)

// 绘本编辑相关
const bookEditVisible = ref(false)
const editingBookIndex = ref(-1)
const editingBook = ref<Book>({
  id: 0,
  title: '',
  description: '',
  coverUrl: '',
  sort: 1,
  pages: []
})
const bookFormRef = ref()

// 页面编辑相关
const pageEditVisible = ref(false)
const editingPageIndex = ref(-1)
const editingPage = ref<BookPage>({
  id: undefined,
  pageNumber: 1,
  imageUrl: '',
  textContent: '',
  chineseTranslation: '',
  textLanguage: 'english',
  officialAudioUrl: '',
  readingDifficulty: 'easy',
  keyWords: []
})
const pageFormRef = ref()
const keyWordsInput = ref('')

// AI翻译相关
const aiTranslating = ref(false)
const batchTranslating = ref(false)

// 分类数据
const categories = ref([
  // 英文分类
  { id: 2, name: '分级阅读', language: 'en', description: '按难度分级的英文阅读绘本' },
  { id: 3, name: '桥梁书', language: 'en', description: '从绘本过渡到章节书的桥梁读物' },
  { id: 4, name: '章节书', language: 'en', description: '适合独立阅读的英文章节书' },
  { id: 5, name: '其它', language: 'en', description: '其他类型的英文绘本' },
  // 中文分类
  { id: 12, name: '古诗词', language: 'zh', description: '中华古典诗词绘本' },
  { id: 13, name: '成语故事', language: 'zh', description: '成语典故和寓意故事' },
  { id: 14, name: '寓言故事', language: 'zh', description: '经典寓言和哲理故事' },
  { id: 15, name: '传统文化', language: 'zh', description: '中华传统文化绘本' },
  { id: 16, name: '科普知识', language: 'zh', description: '科学知识普及绘本' },
  { id: 17, name: '品德教育', language: 'zh', description: '品德修养和教育绘本' }
])

// 根据语言类型筛选分类
const filteredCategories = computed(() => {
  const language = bookSetData.basic.language
  if (!language) return []
  return categories.value.filter(category => category.language === language)
})

// 监听语言类型变化，自动重置分类选择
watch(() => bookSetData.basic.language, (newLanguage, oldLanguage) => {
  if (newLanguage !== oldLanguage && bookSetData.basic.categoryId) {
    // 检查当前选择的分类是否还在新的筛选结果中
    const currentCategoryExists = filteredCategories.value.some(
      category => category.id === bookSetData.basic.categoryId
    )

    if (!currentCategoryExists) {
      // 如果当前分类不在新的筛选结果中，重置为空
      bookSetData.basic.categoryId = null
      ElMessage.info(`语言类型已更改为${getLanguageText(newLanguage)}，请重新选择分类`)
    }
  }
})

// 计算属性
const currentBook = computed((): Book => {
  if (selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]) {
    return bookSetData.books[selectedBookIndex.value]
  }
  return {
    title: '',
    description: '',
    coverUrl: '',
    sort: 1,
    pages: []
  }
})

const totalPages = computed(() => {
  return bookSetData.books.reduce((total, book) => {
    return total + (book.pages?.length || 0)
  }, 0)
})

const canProceed = computed(() => {
  switch (currentStep.value) {
    case 0:
      const basic = bookSetData.basic
      const checks = {
        title: basic.title && basic.title.trim() !== '',
        description: basic.description && basic.description.trim() !== '',
        coverUrl: basic.coverUrl && basic.coverUrl.trim() !== '',
        language: basic.language && basic.language.trim() !== '',
        categoryId: basic.categoryId !== null && basic.categoryId !== undefined,
        difficultyLevel: basic.difficultyLevel && basic.difficultyLevel.trim() !== '',
        ageRange: basic.ageRange && basic.ageRange.trim() !== '',
      }
      return checks.title && checks.description && checks.coverUrl &&
             checks.language && checks.categoryId && checks.difficultyLevel && checks.ageRange
    case 1:
      return bookSetData.books.length > 0
    case 2:
      return totalPages.value > 0
    case 3:
      return true
    default:
      return false
  }
})

const validationResult = computed(() => {
  if (canProceed.value) {
    return {
      title: '验证通过',
      type: 'success' as const,
      description: '所有必填信息已完善，可以提交创建绘本集。'
    }
  } else {
    return {
      title: '验证失败',
      type: 'error' as const,
      description: '请完善当前步骤的必填信息。'
    }
  }
})

// 检查是否有需要翻译的英文页面
const hasEnglishPagesWithoutTranslation = computed(() => {
  if (selectedBookIndex.value === null) return false

  const book = bookSetData.books[selectedBookIndex.value]
  if (!book || !book.pages) return false

  return book.pages.some(page =>
    page.textLanguage === 'english' &&
    page.textContent &&
    page.textContent.trim() &&
    (!page.chineseTranslation || !page.chineseTranslation.trim())
  )
})

// 绘本封面上传URL（动态计算）
const bookCoverUploadUrl = computed(() => {
  return getBusinessUploadUrl('book-cover', bookSetId.value || 0, editingBook.value?.id || 0)
})

// 页面图片上传URL（动态计算）
const pageImageUploadUrl = computed(() => {
  const currentBookId = selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]
    ? bookSetData.books[selectedBookIndex.value].id || 0
    : 0
  return getBusinessUploadUrl('page-image', bookSetId.value || 0, currentBookId, editingPage.value?.pageNumber || 1)
})

// 页面音频上传URL（动态计算）
const pageAudioUploadUrl = computed(() => {
  const currentBookId = selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]
    ? bookSetData.books[selectedBookIndex.value].id || 0
    : 0
  return getBusinessUploadUrl('page-audio', bookSetId.value || 0, currentBookId, editingPage.value?.pageNumber || 1)
})

// 表单验证规则
const basicFormRules = {
  title: [
    { required: true, message: '请输入绘本集标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  language: [
    { required: true, message: '请选择语言类型', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  difficultyLevel: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  ageRange: [
    { required: true, message: '请选择或输入适龄范围', trigger: 'blur' },
    {
      pattern: /^(\d+)-(\d+)岁?$/,
      message: '请输入正确的年龄范围格式，如：3-6岁',
      trigger: 'blur'
    }
  ],
  description: [
    { required: true, message: '请输入绘本集描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  source: [
    { max: 100, message: '来源长度不能超过 100 个字符', trigger: 'blur' }
  ],
  coverUrl: [
    { required: true, message: '请上传绘本集封面', trigger: 'change' }
  ]
}

// 绘本表单验证规则
const bookFormRules = {
  title: [
    { required: true, message: '请输入绘本标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '排序必须在 1 到 100 之间', trigger: 'blur' }
  ]
}

// 页面表单验证规则
const pageFormRules = {
  pageNumber: [
    { required: true, message: '请输入页面编号', trigger: 'blur' },
    { type: 'number' as const, min: 1, max: 100, message: '页面编号必须在 1 到 100 之间', trigger: 'blur' }
  ],
  textContent: [
    { max: 1000, message: '文本内容长度不能超过 1000 个字符', trigger: 'blur' }
  ],
  chineseTranslation: [
    { max: 2000, message: '中文翻译内容长度不能超过 2000 个字符', trigger: 'blur' }
  ],
  textLanguage: [
    { required: true, message: '请选择文本语言', trigger: 'change' }
  ],
  readingDifficulty: [
    { required: true, message: '请选择阅读难度', trigger: 'change' }
  ]
}

// 方法函数
const nextStep = () => {
  if (canProceed.value && currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const getValidationTagType = () => {
  if (canProceed.value) return 'success'
  return 'warning'
}

const getValidationText = () => {
  if (canProceed.value) return '验证通过'
  return '待完善'
}

const getLanguageText = (language: string) => {
  const map = {
    'en': '英文',
    'zh': '中文'
  }
  return map[language] || language
}

// 格式化适龄范围输入
const formatAgeRange = (value: string) => {
  if (!value) return value
  // 自动添加"岁"后缀
  if (/^\d+-\d+$/.test(value)) {
    return value + '岁'
  }
  return value
}

// 处理适龄范围变化
const handleAgeRangeChange = (value: string) => {
  if (value) {
    bookSetData.basic.ageRange = formatAgeRange(value)
  }
}

// 处理适龄范围失焦
const handleAgeRangeBlur = () => {
  if (bookSetData.basic.ageRange) {
    bookSetData.basic.ageRange = formatAgeRange(bookSetData.basic.ageRange)
  }
}

// 业务上传配置
const getBusinessUploadUrl = (type: 'bookset-cover' | 'book-cover' | 'page-image' | 'page-audio', bookSetId?: string | number, bookId?: string | number, pageNumber?: number) => {
  const baseUrl = import.meta.env.VITE_BASE_URL
  let uploadUrl = ''

  // 确保使用正确的绘本集ID（创建模式下使用预分配的ID，编辑模式下使用真实ID）
  const actualBookSetId = bookSetId || bookSetId.value || 0

  // 绘本ID直接使用传入的值
  const actualBookId = bookId || 0

  switch (type) {
    case 'bookset-cover':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${actualBookSetId}/cover`
      break
    case 'book-cover':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${actualBookSetId}/book/${actualBookId}/cover`
      break
    case 'page-image':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${actualBookSetId}/book/${actualBookId}/page/${pageNumber || 1}`
      break
    case 'page-audio':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${actualBookSetId}/book/${actualBookId}/audio?pageNumber=${pageNumber || 1}`
      break
    default:
      uploadUrl = import.meta.env.VITE_UPLOAD_URL
  }
  return uploadUrl
}

// 业务上传头部
const getBusinessUploadHeaders = () => ({
  Authorization: 'Bearer ' + getAccessToken()
})

// 注意：文件URL由后端直接返回完整地址，前端不再进行URL转换

// 文件上传相关
const beforeCoverUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleCoverSuccess = (response: any) => {
  if (response.code === 0) {
    // 记录旧封面路径用于删除（确保是相对路径）
    const oldCoverPath = bookSetData.basic.coverUrl

    // 设置新封面路径（后端返回的已经是相对路径）
    bookSetData.basic.coverUrl = response.data

    // 如果是编辑模式且有旧封面，删除旧文件
    if (isEditMode.value && oldCoverPath && oldCoverPath !== response.data) {
      deleteOldFile(oldCoverPath)
    }

    ElMessage.success('绘本集封面上传成功!')
  } else {
    ElMessage.error('绘本集封面上传失败: ' + response.msg)
  }
}

// 绘本管理相关
const addBook = async () => {
  try {
    // 从服务器获取下一个绘本ID（用于文件上传等操作）
    let bookId: number | undefined

    try {
      bookId = await getNextPictureBookId()
      console.log('获取到下一个绘本ID:', bookId)
    } catch (error) {
      console.warn('获取绘本ID失败，将使用undefined:', error)
      bookId = undefined
    }

    const newBook: Book = {
      id: bookId,
      title: '',
      description: '',
      coverUrl: '',
      sort: bookSetData.books.length + 1,
      pages: [],
      isNewBook: true // 标记为新添加的绘本
    }

    bookSetData.books.push(newBook)
    console.log('绘本添加成功，新绘本:', newBook)
    console.log('当前绘本数组长度:', bookSetData.books.length)
    console.log('当前绘本数组:', bookSetData.books)
    ElMessage.success('绘本添加成功，请编辑绘本信息')
  } catch (error) {
    console.error('添加绘本失败:', error)
    ElMessage.error('添加绘本失败，请稍后重试')
  }
}

const editBook = (index: number) => {
  console.log('编辑绘本，索引:', index, '绘本总数:', bookSetData.books.length)
  console.log('当前绘本数组:', bookSetData.books)

  if (index < 0 || index >= bookSetData.books.length) {
    ElMessage.error(`绘本索引无效: ${index}, 总数: ${bookSetData.books.length}`)
    return
  }

  const book = bookSetData.books[index]
  console.log('要编辑的绘本数据:', book)

  if (!book) {
    ElMessage.error(`绘本数据不存在，索引: ${index}`)
    return
  }

  editingBookIndex.value = index

  // 重置编辑数据
  editingBook.value = {
    id: book.id || 0,
    title: book.title || '',
    description: book.description || '',
    coverUrl: book.coverUrl || '',
    sort: book.sort || (index + 1),
    pages: book.pages ? [...book.pages] : []
  }

  bookEditVisible.value = true
}



const removeBook = async (index: number) => {
  ElMessageBox.confirm('确定要删除这个绘本吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const book = bookSetData.books[index]

    // 如果是编辑模式且绘本有ID（已存在于数据库中），需要调用删除API
    if (isEditMode.value && book.id && !book.isNewBook) {
      try {
        console.log('删除数据库中的绘本，ID:', book.id)
        await deletePictureBook(book.id)
        console.log('绘本从数据库删除成功，ID:', book.id)
      } catch (error) {
        console.error('删除绘本失败:', error)
        ElMessage.error('删除绘本失败，请稍后重试')
        return
      }
    }

    // 从前端数组中移除绘本
    bookSetData.books.splice(index, 1)

    // 如果是编辑模式，重新计算绘本集总绘本数量
    if (isEditMode.value && bookSetId.value) {
      try {
        await updateBookSetBookCount(bookSetId.value)
        console.log('绘本集绘本数量已重新计算，绘本集ID:', bookSetId.value)
      } catch (error) {
        console.warn('重新计算绘本数量失败:', error)
      }
    }

    ElMessage.success('绘本删除成功')
  })
}

// 绘本编辑相关方法
const saveBookEdit = async () => {
  console.log('开始保存绘本编辑')
  console.log('编辑模式:', isEditMode.value)
  console.log('编辑的绘本数据:', editingBook.value)
  console.log('绘本集ID:', bookSetId.value)

  if (!bookFormRef.value) {
    console.log('表单引用不存在')
    return
  }

  try {
    console.log('开始表单验证')
    await bookFormRef.value.validate()
    console.log('表单验证通过')

    // 检查排序是否重复
    const existingSortIndex = bookSetData.books.findIndex((book, index) =>
      book.sort === editingBook.value.sort && index !== editingBookIndex.value
    )

    if (existingSortIndex !== -1) {
      ElMessage.warning(`排序 ${editingBook.value.sort} 已被绘本 "${bookSetData.books[existingSortIndex].title}" 使用，请选择其他排序`)
      return
    }

    // 根据模式决定是否调用后端API
    console.log('检查是否需要调用后端API，编辑模式:', isEditMode.value)

    if (isEditMode.value) {
      // 编辑模式：需要检查绘本是否为新添加的绘本
      const currentBook = bookSetData.books[editingBookIndex.value]
      console.log('编辑模式，当前绘本:', currentBook)
      console.log('是否为新绘本:', currentBook?.isNewBook)

      if (currentBook?.isNewBook) {
        // 新添加的绘本，调用创建API
        console.log('新添加的绘本，调用创建API')
        const createData: PictureBookCreateReqVO = {
          bookSetId: bookSetId.value!,
          title: editingBook.value.title,
          description: editingBook.value.description,
          cover: editingBook.value.coverUrl,
          sortOrder: editingBook.value.sort,
          isActive: true
        }

        console.log('创建数据:', createData)
        const newBookId = await createPictureBook(createData)
        console.log('绘本创建成功，新ID:', newBookId)

        // 更新本地数据中的ID和标记
        editingBook.value.id = newBookId
        currentBook.isNewBook = false // 标记为已存在的绘本

        // 重新计算绘本集总绘本数量
        await updateBookSetBookCount(bookSetId.value!)
        console.log('绘本集绘本数量已重新计算，绘本集ID:', bookSetId.value)

        ElMessage.success('绘本创建成功!')
      } else {
        // 已存在的绘本，调用更新API
        console.log('已存在的绘本，调用更新API')
        const updateData: PictureBookUpdateReqVO = {
          id: editingBook.value.id!,
          bookSetId: bookSetId.value!,
          title: editingBook.value.title,
          description: editingBook.value.description,
          cover: editingBook.value.coverUrl,
          sortOrder: editingBook.value.sort,
          isActive: true
        }

        console.log('更新数据:', updateData)
        await updatePictureBook(updateData)
        console.log('绘本更新成功')

        // 重新计算绘本集总绘本数量
        await updateBookSetBookCount(bookSetId.value!)
        console.log('绘本集绘本数量已重新计算，绘本集ID:', bookSetId.value)

        ElMessage.success('绘本信息更新成功!')
      }
    } else {
      // 创建模式：只更新前端数据，不调用后端API
      ElMessage.success('绘本信息保存成功，将在最终提交时创建!')
    }

    // 更新前端本地数据
    const book = bookSetData.books[editingBookIndex.value]
    book.id = editingBook.value.id
    book.title = editingBook.value.title
    book.description = editingBook.value.description
    book.coverUrl = editingBook.value.coverUrl
    book.sort = editingBook.value.sort

    // 按排序重新排列绘本
    bookSetData.books.sort((a, b) => (a.sort || 0) - (b.sort || 0))

    bookEditVisible.value = false
  } catch (error) {
    console.error('绘本保存失败，详细错误:', error)
    console.error('错误类型:', typeof error)
    console.error('错误消息:', error instanceof Error ? error.message : String(error))
    console.error('错误堆栈:', error instanceof Error ? error.stack : '无堆栈信息')

    const errorMessage = error instanceof Error ? error.message : String(error)
    ElMessage.error(`绘本保存失败: ${errorMessage}`)
  }
}

const cancelBookEdit = () => {
  bookEditVisible.value = false
  editingBookIndex.value = -1
  editingBook.value = {
    id: 0,
    title: '',
    description: '',
    coverUrl: '',
    sort: 1,
    pages: []
  }
}

// 页面管理相关
const addPage = async () => {
  if (selectedBookIndex.value === null) return

  try {
    // 从服务器获取下一个页面ID（用于文件上传等操作）
    let pageId: number | undefined

    try {
      pageId = await getNextBookPageId()
      console.log('获取到下一个页面ID:', pageId)
    } catch (error) {
      console.warn('获取页面ID失败，将使用undefined:', error)
      pageId = undefined
    }

    const newPage: BookPage = {
      id: pageId,
      pageNumber: currentBook.value.pages.length + 1,
      imageUrl: '',
      textContent: '',
      textLanguage: 'english',
      officialAudioUrl: '',
      readingDifficulty: 'easy',
      keyWords: [],
      isNewPage: true // 标记为新添加的页面
    }

    if (!currentBook.value.pages) {
      currentBook.value.pages = []
    }

    currentBook.value.pages.push(newPage)
    ElMessage.success('页面添加成功，请编辑页面内容')
  } catch (error) {
    console.error('添加页面失败:', error)
    ElMessage.error('添加页面失败，请稍后重试')
  }
}

const editPage = (pageIndex: number) => {
  if (selectedBookIndex.value === null) return

  editingPageIndex.value = pageIndex
  const page = currentBook.value.pages[pageIndex]

  editingPage.value = {
    id: page.id,
    pageNumber: page.pageNumber || pageIndex + 1,
    imageUrl: page.imageUrl || '',
    textContent: page.textContent || '',
    chineseTranslation: page.chineseTranslation || '',
    textLanguage: page.textLanguage || 'english',
    officialAudioUrl: page.officialAudioUrl || '',
    readingDifficulty: page.readingDifficulty || 'easy',
    keyWords: [...(page.keyWords || [])]
  }

  keyWordsInput.value = editingPage.value.keyWords.join(', ')
  pageEditVisible.value = true
}

const removePage = (pageIndex: number) => {
  ElMessageBox.confirm('确定要删除这个页面吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const page = currentBook.value.pages[pageIndex]

    // 如果是编辑模式且页面有ID（已存在于数据库中），需要调用删除API
    if (isEditMode.value && page.id && !page.isNewPage) {
      try {
        console.log('删除数据库中的页面，ID:', page.id)
        await deleteBookPage(page.id)
        console.log('页面从数据库删除成功，ID:', page.id)
      } catch (error) {
        console.error('删除页面失败:', error)
        ElMessage.error('删除页面失败，请稍后重试')
        return
      }
    }

    // 从前端数组中移除页面
    currentBook.value.pages.splice(pageIndex, 1)

    // 重新排序页码
    currentBook.value.pages.forEach((page, index) => {
      page.pageNumber = index + 1
    })

    ElMessage.success('页面删除成功')
  })
}

// 页面编辑相关方法
const savePageEdit = async () => {
  if (!pageFormRef.value) return

  try {
    await pageFormRef.value.validate()

    // 根据模式决定是否调用后端API
    if (isEditMode.value) {
      // 编辑模式：需要检查页面是否为新添加的页面
      const currentPage = currentBook.value.pages[editingPageIndex.value]
      console.log('编辑模式，当前页面:', currentPage)
      console.log('是否为新页面:', currentPage?.isNewPage)

      if (currentPage?.isNewPage) {
        // 新添加的页面，调用创建API
        console.log('新添加的页面，调用创建API')

        if (!currentBook.value.id || currentBook.value.id <= 0) {
          ElMessage.error('请先保存绘本信息，然后再添加页面')
          return
        }

        const createData: BookPageCreateReqVO = {
          bookId: currentBook.value.id,
          pageNumber: editingPage.value.pageNumber,
          imageUrl: editingPage.value.imageUrl,
          textContent: editingPage.value.textContent,
          chineseTranslation: editingPage.value.chineseTranslation,
          textLanguage: editingPage.value.textLanguage,
          officialAudioUrl: editingPage.value.officialAudioUrl,
          readingDifficulty: editingPage.value.readingDifficulty,
          keyWords: [...editingPage.value.keyWords]
        }

        console.log('创建页面数据:', createData)
        const newPageId = await createBookPage(createData)
        console.log('页面创建成功，新ID:', newPageId)

        // 更新本地数据中的ID和标记
        editingPage.value.id = newPageId
        currentPage.isNewPage = false // 标记为已存在的页面
        ElMessage.success('页面创建成功!')
      } else {
        // 已存在的页面，调用更新API
        console.log('已存在的页面，调用更新API')
        const updateData: BookPageUpdateReqVO = {
          id: editingPage.value.id!,
          bookId: currentBook.value.id!,
          pageNumber: editingPage.value.pageNumber,
          imageUrl: editingPage.value.imageUrl,
          textContent: editingPage.value.textContent,
          chineseTranslation: editingPage.value.chineseTranslation,
          textLanguage: editingPage.value.textLanguage,
          officialAudioUrl: editingPage.value.officialAudioUrl,
          readingDifficulty: editingPage.value.readingDifficulty,
          keyWords: [...editingPage.value.keyWords]
        }

        console.log('更新页面数据:', updateData)
        await updateBookPage(updateData)
        console.log('页面更新成功')
        ElMessage.success('页面信息更新成功!')
      }
    } else {
      // 创建模式：只更新前端数据，不调用后端API
      ElMessage.success('页面信息保存成功，将在最终提交时创建!')
    }

    // 更新前端本地数据
    const page = currentBook.value.pages[editingPageIndex.value]
    page.id = editingPage.value.id
    page.pageNumber = editingPage.value.pageNumber
    page.imageUrl = editingPage.value.imageUrl
    page.textContent = editingPage.value.textContent
    page.chineseTranslation = editingPage.value.chineseTranslation
    page.textLanguage = editingPage.value.textLanguage
    page.officialAudioUrl = editingPage.value.officialAudioUrl
    page.readingDifficulty = editingPage.value.readingDifficulty
    page.keyWords = [...editingPage.value.keyWords]

    pageEditVisible.value = false
  } catch (error) {
    console.error('页面保存失败:', error)
    ElMessage.error('页面保存失败，请稍后重试')
  }
}

const cancelPageEdit = () => {
  pageEditVisible.value = false
  editingPageIndex.value = -1
  editingPage.value = {
    id: undefined,
    pageNumber: 1,
    imageUrl: '',
    textContent: '',
    chineseTranslation: '',
    textLanguage: 'english',
    officialAudioUrl: '',
    readingDifficulty: 'easy',
    keyWords: []
  }
  keyWordsInput.value = ''
}

// 关键词处理
const updateKeyWords = () => {
  if (keyWordsInput.value) {
    editingPage.value.keyWords = keyWordsInput.value.split(',').map(word => word.trim()).filter(word => word)
  } else {
    editingPage.value.keyWords = []
  }
}

const removeKeyword = (index: number) => {
  editingPage.value.keyWords.splice(index, 1)
  keyWordsInput.value = editingPage.value.keyWords.join(', ')
}

// 清理翻译内容，移除AI添加的说明文字
const cleanTranslationContent = (content: string): string => {
  if (!content) return ''

  // 移除翻译说明部分（通常在括号内或以"翻译说明"开头）
  let cleaned = content
    .replace(/\n*（翻译说明：[^）]*）\n*/g, '') // 移除翻译说明
    .replace(/\n*\(翻译说明：[^)]*\)\n*/g, '') // 移除英文括号的翻译说明
    .replace(/\n*【翻译说明：[^】]*】\n*/g, '') // 移除方括号的翻译说明
    .replace(/\n*翻译说明：[^\n]*\n*/g, '') // 移除单独行的翻译说明
    .trim()

  return cleaned
}

// AI翻译处理
const handleAiTranslate = async () => {
  if (!editingPage.value.textContent || !editingPage.value.textContent.trim()) {
    ElMessage.warning('请先输入英文文本内容')
    return
  }

  // 如果已有翻译内容，询问是否覆盖
  if (editingPage.value.chineseTranslation && editingPage.value.chineseTranslation.trim()) {
    try {
      await ElMessageBox.confirm(
        '当前已有翻译内容，是否要用AI翻译结果覆盖？',
        '确认覆盖',
        {
          confirmButtonText: '覆盖',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return // 用户取消
    }
  }

  try {
    aiTranslating.value = true

    console.log('开始AI翻译，文本内容:', editingPage.value.textContent)

    const response = await translateText({
      content: editingPage.value.textContent,
      operation: 'translate',
      sourceLanguage: 'en',
      targetLanguage: 'zh'
    })

    console.log('AI翻译响应:', response)

    // 检查响应并提取翻译内容
    if (response && response.content) {
      // 清理翻译内容，移除可能的说明文字
      const cleanedContent = cleanTranslationContent(response.content)
      editingPage.value.chineseTranslation = cleanedContent
      ElMessage.success('AI翻译完成！您可以在此基础上进行修改')
    } else {
      console.error('AI翻译响应格式异常:', response)
      throw new Error('翻译响应格式异常')
    }
  } catch (error) {
    console.error('AI翻译失败，详细错误:', error)
    console.error('错误类型:', typeof error)
    console.error('错误消息:', error instanceof Error ? error.message : String(error))

    let errorMessage = 'AI翻译失败，请稍后重试'
    if (error instanceof Error) {
      if (error.message.includes('404')) {
        errorMessage = 'AI翻译服务接口不存在，请联系管理员'
      } else if (error.message.includes('500')) {
        errorMessage = 'AI翻译服务内部错误，请稍后重试'
      } else if (error.message.includes('网络')) {
        errorMessage = '网络连接失败，请检查网络后重试'
      } else {
        errorMessage = `AI翻译失败: ${error.message}`
      }
    }

    ElMessage.error(errorMessage)
  } finally {
    aiTranslating.value = false
  }
}

// 批量翻译处理
const handleBatchTranslate = async () => {
  if (selectedBookIndex.value === null) return

  const book = bookSetData.books[selectedBookIndex.value]
  if (!book || !book.pages) return

  // 找出需要翻译的页面
  const pagesToTranslate = book.pages.filter(page =>
    page.textLanguage === 'english' &&
    page.textContent &&
    page.textContent.trim() &&
    (!page.chineseTranslation || !page.chineseTranslation.trim())
  )

  if (pagesToTranslate.length === 0) {
    ElMessage.info('当前绘本没有需要翻译的英文页面')
    return
  }

  try {
    await ElMessageBox.confirm(
      `将为当前绘本的 ${pagesToTranslate.length} 个页面生成AI翻译，是否继续？`,
      '批量AI翻译',
      {
        confirmButtonText: '开始翻译',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
  } catch {
    return // 用户取消
  }

  batchTranslating.value = true
  let successCount = 0
  let failCount = 0

  try {
    // 显示进度提示
    ElMessage.info(`开始批量翻译 ${pagesToTranslate.length} 个页面...`)

    // 逐个翻译页面（避免并发过多导致API限制）
    for (let i = 0; i < pagesToTranslate.length; i++) {
      const page = pagesToTranslate[i]

      try {
        const response = await translateText({
          content: page.textContent,
          operation: 'translate',
          sourceLanguage: 'en',
          targetLanguage: 'zh'
        })

        if (response && response.code === 0) {
          page.chineseTranslation = response.data.content
          successCount++
        } else {
          throw new Error(response?.msg || '翻译失败')
        }
      } catch (error) {
        console.error(`页面 ${page.pageNumber} 翻译失败:`, error)
        failCount++
      }

      // 添加延迟避免API频率限制
      if (i < pagesToTranslate.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
    }

    // 显示结果
    if (successCount > 0) {
      ElMessage.success(`批量翻译完成！成功：${successCount} 个，失败：${failCount} 个`)
    } else {
      ElMessage.error('批量翻译失败，请稍后重试')
    }

  } catch (error) {
    console.error('批量翻译失败:', error)
    ElMessage.error('批量翻译失败，请稍后重试')
  } finally {
    batchTranslating.value = false
  }
}

// 文件上传相关
const beforeBookCoverUpload = (file: File) => {
  return beforeCoverUpload(file)
}

const handleBookCoverSuccess = (response: any) => {
  if (response.code === 0) {
    // 记录旧封面路径用于删除
    const oldCoverPath = editingBook.value.coverUrl

    // 设置新封面路径
    editingBook.value.coverUrl = response.data

    // 如果是编辑模式且有旧封面，删除旧文件
    if (isEditMode.value && oldCoverPath && oldCoverPath !== response.data) {
      deleteOldFile(oldCoverPath)
    }

    ElMessage.success('绘本封面上传成功!')
  } else {
    ElMessage.error('绘本封面上传失败: ' + response.msg)
  }
}

const beforePageImageUpload = (file: File) => {
  return beforeCoverUpload(file)
}

const handlePageImageSuccess = (response: any) => {
  if (response.code === 0) {
    // 记录旧图片路径用于删除
    const oldImagePath = editingPage.value.imageUrl

    // 设置新图片路径
    editingPage.value.imageUrl = response.data

    // 如果是编辑模式且有旧图片，删除旧文件
    if (isEditMode.value && oldImagePath && oldImagePath !== response.data) {
      deleteOldFile(oldImagePath)
    }

    ElMessage.success('页面图片上传成功!')
  } else {
    ElMessage.error('页面图片上传失败: ' + response.msg)
  }
}

const beforeAudioUpload = (file: File) => {
  const isAudio = file.type.startsWith('audio/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isAudio) {
    ElMessage.error('只能上传音频格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传音频大小不能超过 10MB!')
    return false
  }
  return true
}

const handleAudioSuccess = (response: any) => {
  if (response.code === 0) {
    // 记录旧音频路径用于删除
    const oldAudioPath = editingPage.value.officialAudioUrl

    // 设置新音频路径
    editingPage.value.officialAudioUrl = response.data

    // 如果是编辑模式且有旧音频，删除旧文件
    if (isEditMode.value && oldAudioPath && oldAudioPath !== response.data) {
      deleteOldFile(oldAudioPath)
    }

    ElMessage.success('音频上传成功!')
  } else {
    ElMessage.error('音频上传失败: ' + response.msg)
  }
}

const removeAudio = () => {
  editingPage.value.officialAudioUrl = ''
  ElMessage.success('音频删除成功!')
}

// 删除旧文件的方法
const deleteOldFile = async (pathOrUrl: string) => {
  try {
    // 确保传递的是路径而不是完整URL
    let filePath = pathOrUrl

    // 如果是完整URL，提取路径部分
    if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
      const url = new URL(filePath)
      filePath = url.pathname
    }

    const baseUrl = import.meta.env.VITE_BASE_URL
    const deleteUrl = `${baseUrl}/admin-api/reading/book-file/delete?path=${encodeURIComponent(filePath)}`

    await request.delete({
      url: deleteUrl,
      headers: {
        Authorization: 'Bearer ' + getAccessToken()
      }
    })

    console.log('旧文件删除成功:', filePath)
  } catch (error) {
    console.warn('删除旧文件失败:', pathOrUrl, error)
    // 不显示错误消息，因为这不是关键操作
  }
}



// 主要操作方法
const handleClose = () => {
  emit('close')
}

const handleSubmit = async () => {
  if (!canProceed.value) {
    ElMessage.warning('请完善所有必填信息')
    return
  }

  submitting.value = true
  try {
    if (isEditMode.value) {
      // 编辑模式
      const updateData: BookSetUpdateReqVO = {
        id: props.bookSetId!,
        title: bookSetData.basic.title,
        cover: bookSetData.basic.coverUrl,
        description: bookSetData.basic.description,
        categoryId: bookSetData.basic.categoryId!,
        ageRange: bookSetData.basic.ageRange,
        source: bookSetData.basic.source,
        difficultyLevel: bookSetData.basic.difficultyLevel,
        language: bookSetData.basic.language,
        isRecommended: bookSetData.basic.isRecommended,
        isActive: bookSetData.basic.isActive
      }

      await updateBookSet(updateData)

      // 重新计算绘本集总绘本数量
      await updateBookSetBookCount(props.bookSetId!)
      console.log('绘本集绘本数量已重新计算，绘本集ID:', props.bookSetId)

      ElMessage.success('绘本集更新成功!')
    } else {
      // 创建模式：需要批量创建绘本集、绘本和页面数据
      console.log('开始创建模式提交，绘本数量:', bookSetData.books.length)

      // 1. 创建绘本集
      const createData: BookSetCreateReqVO = {
        title: bookSetData.basic.title,
        cover: bookSetData.basic.coverUrl,
        description: bookSetData.basic.description,
        categoryId: bookSetData.basic.categoryId!,
        ageRange: bookSetData.basic.ageRange,
        source: bookSetData.basic.source,
        difficultyLevel: bookSetData.basic.difficultyLevel,
        language: bookSetData.basic.language,
        isRecommended: bookSetData.basic.isRecommended,
        isActive: bookSetData.basic.isActive
      }

      const bookSetResponse = await createBookSet(createData)
      console.log('绘本集创建响应:', bookSetResponse)

      // 前端request工具已经自动提取了data字段，所以bookSetResponse就是绘本集ID
      const newBookSetId = bookSetResponse
      console.log('绘本集创建成功，ID:', newBookSetId)
      console.log('newBookSetId 类型:', typeof newBookSetId, '值:', newBookSetId)

      if (!newBookSetId) {
        throw new Error('创建绘本集失败，未获取到有效的绘本集ID')
      }

      // 2. 批量创建绘本
      if (bookSetData.books.length > 0) {
        // 过滤掉没有标题的绘本（可能是用户添加了但没有编辑的）
        const validBooks = bookSetData.books.filter(book => book.title && book.title.trim() !== '')

        if (validBooks.length > 0) {
          const booksToCreate: PictureBookCreateReqVO[] = validBooks.map(book => ({
            bookSetId: newBookSetId,
            title: book.title,
            description: book.description,
            cover: book.coverUrl,
            sortOrder: book.sort,
            isActive: true
          }))

          console.log('准备创建绘本，数量:', validBooks.length)
          console.log('绘本数据详情:', booksToCreate)
          console.log('每个绘本的bookSetId:', booksToCreate.map(book => book.bookSetId))

          const createdBookIds = await batchCreatePictureBooks(booksToCreate)
          console.log('绘本创建成功，IDs:', createdBookIds)

          // 3. 批量创建页面
          const allPagesToCreate: BookPageCreateReqVO[] = []

          validBooks.forEach((book, bookIndex) => {
            if (book.pages && book.pages.length > 0) {
              const bookId = createdBookIds[bookIndex]
              book.pages.forEach(page => {
                allPagesToCreate.push({
                  bookId: bookId,
                  pageNumber: page.pageNumber,
                  imageUrl: page.imageUrl,
                  textContent: page.textContent,
                  textLanguage: page.textLanguage,
                  officialAudioUrl: page.officialAudioUrl,
                  readingDifficulty: page.readingDifficulty,
                  keyWords: page.keyWords
                })
              })
            }
          })

          if (allPagesToCreate.length > 0) {
            console.log('准备创建页面:', allPagesToCreate)
            const createdPageIds = await batchCreateBookPages(allPagesToCreate)
            console.log('页面创建成功，IDs:', createdPageIds)
          }
        } else {
          console.log('没有有效的绘本需要创建')
        }
      } else {
        console.log('没有绘本数据需要创建')
      }

      // 重新计算绘本集总绘本数量
      await updateBookSetBookCount(newBookSetId)
      console.log('绘本集绘本数量已重新计算，绘本集ID:', newBookSetId)

      ElMessage.success('绘本集及所有内容创建成功!')
    }

    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 初始化数据
const initData = async () => {
  if (isEditMode.value && props.bookSetId) {
    try {
      // 1. 获取绘本集基本信息
      const bookSetData_response = await getBookSet(props.bookSetId)

      console.log('绘本集数据响应:', bookSetData_response)

      // 验证必要字段
      if (!bookSetData_response || !bookSetData_response.title) {
        throw new Error('绘本集数据不完整，缺少标题字段')
      }

      // 填充基本信息
      bookSetData.basic.title = bookSetData_response.title || ''
      bookSetData.basic.description = bookSetData_response.description || ''
      bookSetData.basic.coverUrl = bookSetData_response.cover || ''
      bookSetData.basic.categoryId = bookSetData_response.categoryId || null
      bookSetData.basic.ageRange = bookSetData_response.ageRange || ''
      bookSetData.basic.source = bookSetData_response.source || ''
      bookSetData.basic.difficultyLevel = bookSetData_response.difficultyLevel || ''
      bookSetData.basic.language = bookSetData_response.language || 'en'
      bookSetData.basic.isRecommended = bookSetData_response.isRecommended || false
      bookSetData.basic.isActive = bookSetData_response.isActive !== false

      bookSetId.value = bookSetData_response.id

      // 2. 获取绘本列表
      try {
        const books = await getPictureBooksByBookSetId(props.bookSetId)

        console.log('绘本列表响应:', books)

        // 确保books是数组
        const booksArray = Array.isArray(books) ? books : []
        console.log('绘本数组:', booksArray)

        // 3. 为每个绘本获取页面数据
        const booksWithPages = await Promise.all(
          books.map(async (book: any) => {
            try {
              const pages = await getBookPagesByBookId(book.id)

              console.log(`绘本 ${book.id} 的页面响应:`, pages)

              // 确保pages是数组
              const pagesArray = Array.isArray(pages) ? pages : []
              console.log(`绘本 ${book.id} 的页面数组:`, pagesArray)

              // 检查中文翻译数据
              const translationPages = pagesArray.filter((page: any) => page.chineseTranslation)
              if (translationPages.length > 0) {
                console.log(`绘本 ${book.id} 包含 ${translationPages.length} 页中文翻译数据`)
              }

              return {
                id: book.id,
                title: book.title || '',
                description: book.description || '',
                coverUrl: book.cover || '',
                sort: book.sortOrder || 1,
                isNewBook: false, // 从数据库加载的绘本不是新绘本
                pages: pagesArray.map((page: any) => ({
                  id: page.id,
                  pageNumber: page.pageNumber,
                  imageUrl: page.imageUrl || '',
                  textContent: page.textContent || '',
                  chineseTranslation: page.chineseTranslation || '',
                  textLanguage: page.textLanguage || 'english',
                  officialAudioUrl: page.officialAudioUrl || '',
                  readingDifficulty: page.readingDifficulty || 'easy',
                  keyWords: page.keyWords || [],
                  isNewPage: false // 从数据库加载的页面不是新页面
                }))
              }
            } catch (pageError) {
              console.error(`获取绘本 ${book.id} 的页面数据失败:`, pageError)
              return {
                id: book.id,
                title: book.title || '',
                description: book.description || '',
                coverUrl: book.cover || '',
                sort: book.sortOrder || 1,
                isNewBook: false, // 从数据库加载的绘本不是新绘本
                pages: []
              }
            }
          })
        )

        // 按排序字段排序
        booksWithPages.sort((a, b) => (a.sort || 0) - (b.sort || 0))
        bookSetData.books = booksWithPages

        ElMessage.success('绘本集数据加载完成')
      } catch (booksError) {
        console.error('获取绘本列表失败:', booksError)
        ElMessage.warning('绘本集基本信息已加载，但绘本列表加载失败')
      }

    } catch (error) {
      console.error('获取绘本集数据失败:', error)
      ElMessage.error('获取绘本集数据失败')
    }
  } else {
    // 创建模式：获取预分配的绘本集ID用于文件上传
    try {
      const nextId = await getNextBookSetId()
      bookSetId.value = nextId
      console.log('获取预分配绘本集ID:', bookSetId.value)
    } catch (error) {
      console.warn('获取预分配ID失败，将在提交时获取:', error)
      bookSetId.value = 0 // 使用0作为临时ID
    }
  }
}

// 监听props变化，重新初始化数据
watch(() => [props.mode, props.bookSetId], () => {
  initData()
}, { immediate: true })

// 组件挂载时初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.bookset-manager {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.step-navigation {
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.main-content {
  margin-bottom: 20px;
}

.edit-area {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.step-content {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.category-tips,
.age-range-tips,
.source-tips,
.recommend-tips {
  margin-top: 5px;
}

.cover-uploader .cover-image {
  width: 120px;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
}

.cover-uploader .cover-placeholder {
  width: 120px;
  height: 160px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.cover-uploader .cover-placeholder:hover {
  border-color: #409eff;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.upload-tip .el-text {
  display: flex;
  align-items: center;
  gap: 4px;
}

.cover-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.cover-text {
  color: #8c939d;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.books-list {
  padding: 20px;
}

.book-card {
  height: 100%;
}

.book-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.book-actions {
  display: flex;
  gap: 8px;
}

.book-display {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.book-cover-container {
  text-align: center;
}

.book-cover {
  width: 80px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.book-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
}

.book-description {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.book-stats {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.pages-container {
  padding: 20px;
}

.pages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.page-card {
  height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-actions {
  display: flex;
  gap: 8px;
}

.page-display {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.page-image-container {
  text-align: center;
}

.page-image {
  width: 100%;
  max-width: 200px;
  height: auto;
  border-radius: 4px;
}

.image-placeholder {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
}

.text-content p {
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

.audio-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.preview-area {
  position: sticky;
  top: 20px;
}

.preview-card {
  height: fit-content;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.preview-content {
  padding: 20px;
}

.step-preview h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
}

.cover-section {
  text-align: center;
  margin-bottom: 16px;
}

.preview-cover {
  width: 80px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.info-item .label {
  font-weight: 500;
  color: #666;
}

.empty-preview {
  text-align: center;
  padding: 20px;
}

.books-preview {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.book-preview-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.book-cover {
  flex-shrink: 0;
}

.book-cover-img {
  width: 40px;
  height: 50px;
  object-fit: cover;
  border-radius: 2px;
}

.no-cover {
  width: 40px;
  height: 50px;
  background: #f5f5f5;
  border-radius: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #999;
}

.book-info {
  flex: 1;
  min-width: 0;
}

.book-title {
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-stats {
  display: flex;
  gap: 4px;
}

.pages-stats {
  text-align: center;
}

.stat-item {
  display: inline-block;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.final-stats {
  text-align: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.stat-card {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.book-edit-dialog .book-cover-uploader .book-cover-image {
  width: 100px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.book-edit-dialog .book-cover-placeholder {
  width: 100px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.page-edit-dialog .page-image-uploader .page-image-preview {
  width: 200px;
  height: auto;
  border-radius: 4px;
}

.page-edit-dialog .page-image-placeholder {
  width: 200px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-icon {
  font-size: 24px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
}

.keywords-display {
  margin-top: 8px;
}

.audio-upload-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.audio-preview {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 300px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.bookset-overview h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
}

/* 绘本编辑弹窗样式 */
.book-edit-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.book-cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
  width: 120px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.book-cover-uploader .el-upload:hover {
  border-color: #409eff;
}

.book-cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-cover-placeholder {
  text-align: center;
  color: #8c939d;
}

.book-cover-placeholder .cover-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.book-cover-placeholder .cover-text {
  font-size: 12px;
}

/* 模式指示器样式 */
.mode-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  gap: 12px;
}

.mode-description {
  color: #606266;
  font-size: 14px;
}

/* 翻译输入框样式 */
.form-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #e1f5fe;
  border-radius: 4px;
  color: #0277bd;
  font-size: 12px;
}

.form-tip .el-icon {
  font-size: 14px;
  color: #0288d1;
}

/* AI翻译相关样式 */
.translation-input-container {
  position: relative;
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

.translation-textarea {
  flex: 1;
}

.ai-translate-btn {
  margin-top: 0;
  height: 32px;
  min-width: 80px;
  font-size: 12px;
  white-space: nowrap;
}

.ai-translate-btn .el-icon {
  margin-right: 4px;
}

.ai-translate-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
